package com.rupyi.service.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.common.core.mbp.page.PageQuery;
import com.ruoyi.common.core.mbp.page.TableDataInfo;
import com.rupyi.service.domain.Example;
import com.rupyi.service.domain.vo.ExampleItemVo;
import com.rupyi.service.domain.vo.ExampleVo;
import com.rupyi.service.mapper.ExampleMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Service
@Transactional(rollbackFor = Exception.class)
@RequiredArgsConstructor
public class ExampleService {

    private final ExampleMapper baseMapper;

    private final ExampleItemService exampleItemService;

    public TableDataInfo<ExampleVo> retrieveList(ExampleVo entity, PageQuery pageQuery) {
        QueryWrapper<ExampleVo> lqw = new QueryWrapper<>();
        lqw.eq(StringUtils.isNotBlank(entity.getId()), "t.id", entity.getId());
        lqw.eq("t.delete_flag", "0");
        lqw.orderByDesc("t.create_time");

        Page<ExampleVo> page = baseMapper.retrieveList(pageQuery.build(), lqw);
        List<ExampleVo> records = page.getRecords();
        if (CollectionUtil.isEmpty(records)) {
            return TableDataInfo.build(page);
        }

        List<String> pidList = records.stream()
            .map(ExampleVo::getId)
            .collect(Collectors.toList());
        List<ExampleItemVo> exampleItemVos = exampleItemService.retrieveByPids(pidList);
        Map<String, List<ExampleItemVo>> pidGroup = exampleItemVos.stream()
            .collect(Collectors.groupingBy(
                ExampleItemVo::getPid
            ));
        for (ExampleVo record : records) {
            List<ExampleItemVo> tmpList = pidGroup.get(record.getId());
            record.setItemList(tmpList);
        }

        return TableDataInfo.build(page);
    }

    public ExampleVo retrieveVoById(String id) {
        return baseMapper.selectVoById(id);
    }

    public int create(ExampleVo entity) {
        Example example = BeanUtil.copyProperties(entity, Example.class);
        return baseMapper.insert(example);
    }
}
